import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, FormInstance } from "element-plus";
import { useRoute } from "vue-router";
import { ref, reactive, nextTick, watch, onMounted, computed, onUnmounted } from "vue";
import {
  ProcustomGetFX,
  ProCustomGetProCustom,
  ProCustomGetCustomHost,
  ProCustomInsertCustomBase
} from "@/api/stu/InsuranceData"
import { emitter } from "@/utils/mitt";
import qs from "qs";
export function usePDataIntegration() {
  const route = useRoute();
  const Visible = ref(false);
  const loading = ref(false);
  const btnload = ref(false);
  const dataList = ref();
  const MySignIn = ref("all");
  const SetMyJSonar = ref();// 保存子组件内容
  const RefScreenConformity = ref();
  const SelectCustomerBase = ref();
  const RefCustomerGroup = ref();
  const CustomerGroup = reactive({
    name: ""
  })
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 30,
    currentPage: 1,
    pageSizes: [5, 10, 30],
    background: true
  });

  const columns = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    },
    {
      label: "姓名",
      prop: "name",
    }, {
      label: "性别",
      prop: "sex",
    }, {
      label: "年龄",
      prop: "age",
    }, {
      label: "民族",
      prop: "nation",
    }, {
      label: "身份证号",
      prop: "idCard",
    }, {
      label: "电话号码",
      prop: "phone",
    }, {
      label: "婚姻状况",
      prop: "marriageState",
    }, {
      label: "累计逾期次数",
      prop: "accBeOverdue",
      width: 100
    }, {
      label: "当前逾期期数",
      prop: "beOverdue",
      width: 100
    }, {
      label: "购买保险",
      prop: "byInsure",
    }, {
      label: "职业",
      prop: "career",
    }, {
      label: "常购服装码数",
      prop: "clothingNumber",
      width: 100
    },
    // {
    //   label: "创建时间",
    //   prop: "createTime",
    //   width: 150
    // },
    {
      label: "酒驾记录",
      prop: "drunkDriving",
    }, {
      label: "教育程度",
      prop: "educationLevel",
    }, {
      label: "健康状况",
      prop: "healthState",
    }, {
      label: "最高逾期期数",
      prop: "highestBeOverdue",
      width: 100
    },
    {
      label: "违章停车",
      prop: "illegalParking",
    }, {
      label: "是否产生高额医疗费",
      prop: "isHigtAmount",
    }, {
      label: "是否吸烟",
      prop: "isSmoke",
    }, {
      label: "是否在肿瘤或心脑血管科室就诊过",
      prop: "isTumor",
      width: 150
    }, {
      label: "每月消费与收入占比",
      prop: "monthConInProp",
    }, {
      label: "省份",
      prop: "province",
    }, {
      label: "搜索次数",
      prop: "searchCount",
    }, {
      label: "搜索关键词",
      prop: "searchkeyword",
    }, {
      label: "理赔原因",
      prop: "settleClaim",
    }, {
      label: "日均睡眠时长",
      prop: "sleepTime",
      width: 100
    }, {
      label: "超速行驶",
      prop: "speeding",
    }, {
      label: "每周外卖频率",
      prop: "takeaway",
      width: 100
    }, {
      label: "年收入",
      prop: "yearIncome",
    },

  ];

  // 创建客户群
  function getCustomerGroup(RefCustomerGroup: FormInstance | undefined) {
    (RefCustomerGroup as any).validate(async valid => {
      if (!valid) return;
      btnload.value = true;
      const data = {
        pageIndex: pagination.currentPage,
        pageCount: pagination.pageSize,
        planId: route.query.planId,
        taskId: route.query.taskId,
        name: CustomerGroup.name,
        arr: SetMyJSonar.value
      }
      const res = await ProCustomInsertCustomBase(data);
      if (res.success) {
        ElMessage.success(res.msg);
        HideVisible(RefCustomerGroup);
        GetSeleteList()
        emitter.emit("clearChooses")
        btnload.value = false;
      } else {
        ElMessage.error(res.msg);
        setTimeout(() => { btnload.value = false; }, 1500)
      }
    })
  }

  // 获取创建的客户群
  async function GetSeleteList() {
    const data = qs.stringify({
      planId: route.query.planId,
      taskId: route.query.taskId,
    })
    const res = await ProCustomGetCustomHost(data);
    if (res.success) SelectCustomerBase.value = res.data;
    else ElMessage.error(res.msg);
  }

  //
  async function getListData(row) {
    // 获取客户群列表
    SetMyJSonar.value = row;
    const data = {
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize,
      planId: route.query.planId,
      taskId: route.query.taskId,
      name: CustomerGroup.name,
      arr: row || []
    }
    const res = await ProCustomGetProCustom(data);
    if (res.success) {
      dataList.value = res?.data?.items;
      pagination.total = res?.data?.totalCount;
    } else {
      ElMessage.error(res.msg)
    }
  }

  // 查看客户群数据
  async function SelectDataById(row) {
    if (row == "all") {
      emitter.emit("clearChooses")
    } else {
      const data = {
        pageIndex: pagination.currentPage,
        pageCount: pagination.pageSize,
        planId: route.query.planId,
        taskId: route.query.taskId,
        chId: row   //--客户群Id
      }
      const res = await ProcustomGetFX(data);
      if (res.success) {
        dataList.value = res?.data?.list;
        pagination.total = res?.data?.totalCount;
        emitter.emit("ViewSecurities", res?.data?.arr || [])
      } else {
        ElMessage.error(res.msg)
      }
    }
  }

  // 清空选择的客户群
  emitter.on("clearChoose", () => {
    MySignIn.value = "all";
    SetMyJSonar.value = ""
    getListData(SetMyJSonar.value);
  })


  // 创建客户群 -- 窗口
  emitter.on('EM_openVisible', async (row) => {
    SetMyJSonar.value = eval(row.value)
    Visible.value = true;
  })

  emitter.on("EmitCustomerGroup", async (row) => {
    getListData(row);
  })

  function handleSizeChange(val) {
    if (MySignIn.value !== "all") {
      SelectDataById(MySignIn.value)
    } else {
      getListData(SetMyJSonar.value)
    }
  }

  function handleCurrentChange(val) {
    if (MySignIn.value !== "all") {
      SelectDataById(MySignIn.value)
    } else {
      getListData(SetMyJSonar.value)
    }
  }

  function HideVisible(row: FormInstance | undefined) {
    row.resetFields();
    Visible.value = false;
  }

  onUnmounted(() => {
    emitter.off("ViewSecurities")
    emitter.off("clearChooses")
  })

  onMounted(() => {
    getListData(undefined);
    GetSeleteList()
  })

  return {
    btnload,
    columns,
    loading,
    Visible,
    dataList,
    MySignIn,
    pagination,
    CustomerGroup,
    RefCustomerGroup,
    RefScreenConformity,
    SelectCustomerBase,
    SelectDataById,
    GetSeleteList,
    HideVisible,
    getCustomerGroup,
    handleSizeChange,
    handleCurrentChange
  }
}
